#include "networkdetaildialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QHeaderView>
#include <QFrame>
#include <QFont>
#include <QDebug>
#include <QRegularExpression>
#include <QSizePolicy>
#include <QBrush>
#include <QColor>
#include <QGuiApplication>
#include <QClipboard>
#include <QMenu>
#include <QAction>
#include <QProcess>
#include <QFile>

NetworkDetailDialog::NetworkDetailDialog(const ConnectionInfo &connInfo, const DeviceInfo &devInfo, QWidget *parent)
    : QDialog(parent)
{
    setWindowFlags((windowFlags() & ~Qt::WindowMaximizeButtonHint & ~Qt::WindowMinimizeButtonHint) | Qt::Dialog | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
    setWindowTitle(QString("%1 详细信息").arg(devInfo.name));
    setFixedSize(470, 600);
    setFixedSize(this->size());
    setupUI();
    fillTable(connInfo, devInfo);
}

void NetworkDetailDialog::setupUI()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(16, 16, 16, 16);
    mainLayout->setSpacing(0);

    QHBoxLayout *titleLayout = new QHBoxLayout;
    titleLayout->setContentsMargins(0,0,0,0);
    QLabel *title = new QLabel("网络连接详细信息(D):", this);
    QFont titleFont("Microsoft YaHei", 11, QFont::Bold);
    title->setFont(titleFont);
    int tH = title->fontMetrics().height();
    title->setMinimumHeight(tH + 2);
    title->setMaximumHeight(tH + 2);
    title->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    titleLayout->addWidget(title);
    mainLayout->addLayout(titleLayout);

    QFrame *line = new QFrame(this);
    line->setFrameShape(QFrame::HLine);
    line->setStyleSheet("color: #e0e0e0; background: #e0e0e0;");
    line->setFixedHeight(1);
    mainLayout->addWidget(line);

    table = new QTableWidget(this);
    table->setColumnCount(2);
    table->setHorizontalHeaderLabels(QStringList() << "属性" << "值");
    table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
    table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
    table->verticalHeader()->setVisible(false);
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);
    table->setSelectionBehavior(QAbstractItemView::SelectRows);
    table->setSelectionMode(QAbstractItemView::SingleSelection);
    table->setShowGrid(false);
    table->setFrameShape(QFrame::NoFrame);
    table->setLineWidth(0);
    table->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    table->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    QFont tableFont("Microsoft YaHei", 10);
    table->setFont(tableFont);
    table->setAlternatingRowColors(true);
    table->setStyleSheet(
        "QTableWidget { background: white; border: none; alternate-background-color: #f7f7f7; } "
        "QHeaderView::section { background: #f3f3f3; font-weight: bold; border: none; font-family: 'Microsoft YaHei'; font-size: 10pt; height: 28px; } "
        "QTableWidget::item:selected { background: #0078d7; color: #fff; } "
        "QTableWidget::item { padding: 6px 12px; font-family: 'Microsoft YaHei'; font-size: 10pt; color: #222; } "
    );
    table->horizontalHeader()->setFont(QFont("Microsoft YaHei", 10, QFont::Bold));
    table->setContentsMargins(0, 0, 0, 0);
    table->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding);
    table->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    table->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    table->setWordWrap(false);
    table->setFocusPolicy(Qt::StrongFocus);
    table->setSelectionMode(QAbstractItemView::SingleSelection);
    mainLayout->addWidget(table, 0, Qt::AlignTop);

    // 表格下方加分割线
    QFrame *bottomLine = new QFrame(this);
    bottomLine->setFrameShape(QFrame::HLine);
    bottomLine->setStyleSheet("color: #e0e0e0; background: #e0e0e0;");
    bottomLine->setFixedHeight(1);
    mainLayout->addWidget(bottomLine);
    mainLayout->addSpacing(8);
    QHBoxLayout *btnLayout = new QHBoxLayout;
    btnLayout->setContentsMargins(0,0,10,10);
    btnLayout->setSpacing(0);
    btnLayout->addStretch();
    btnClose = new QPushButton("关闭(C)", this);
    btnClose->setFixedSize(100, 32);
    btnClose->setFont(QFont("Microsoft YaHei", 10));
    btnLayout->addWidget(btnClose);
    mainLayout->addLayout(btnLayout);
    connect(btnClose, &QPushButton::clicked, this, &QDialog::accept);
    setFixedWidth(500);
    this->adjustSize();

    // 右键菜单复制功能
    table->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(table, &QTableWidget::customContextMenuRequested, this, [this](const QPoint &pos) {
        QModelIndex idx = table->indexAt(pos);
        if (!idx.isValid()) return;
        QMenu menu(this);
        QAction *copyAction = menu.addAction("复制");
        QAction *selected = menu.exec(table->viewport()->mapToGlobal(pos));
        if (selected == copyAction) {
            QString text = table->item(idx.row(), idx.column()) ? table->item(idx.row(), idx.column())->text() : "";
            QClipboard *clipboard = QGuiApplication::clipboard();
            clipboard->setText(text);
        }
    });
    // 双击复制功能
    connect(table, &QTableWidget::itemDoubleClicked, this, [](QTableWidgetItem *item){
        if (!item) return;
        QClipboard *clipboard = QGuiApplication::clipboard();
        clipboard->setText(item->text());
    });
}

void NetworkDetailDialog::fillTable(const ConnectionInfo &conn, const DeviceInfo &dev)
{
    QStringList props, vals;
    props << "连接特定的 DNS 后缀" << "描述" << "物理地址" << "已启用 DHCP" << "IPv4 地址" << "IPv4 子网掩码" << "IPv4 默认网关" << "IPv4 DNS 服务器" << "IPv4 WINS 服务器" << "已启用 NetBIOS over TCP/IP" << "连接-本地 IPv6 地址" << "IPv6 默认网关";
    vals << "";
    vals << (!dev.model.isEmpty() ? dev.model : dev.driver);
    vals << (!dev.macAddress.isEmpty() ? dev.macAddress : conn.macAddress);

    // 新增：bond-slave-*连接显示真实设备状态
    QString realIp, realMask, realGw, realDns, realDhcp = "否";
    if (conn.name.startsWith("bond-slave-") && !conn.device.isEmpty()) {
        // 1. 获取IP和掩码（从属网卡通常没有独立IP）
        QProcess ipProc;
        ipProc.start("ip", QStringList() << "addr" << "show" << conn.device);
        ipProc.waitForFinished(1000);
        QString ipOut = QString::fromUtf8(ipProc.readAllStandardOutput());
        QRegularExpression ipRe("inet ([0-9.]+)/(\\d+)");
        QRegularExpressionMatch match = ipRe.match(ipOut);
        if (match.hasMatch()) {
            realIp = match.captured(1);
            int cidr = match.captured(2).toInt();
            quint32 mask = (cidr >= 0 && cidr <= 32) ? ((0xFFFFFFFF << (32 - cidr)) & 0xFFFFFFFF) : 0;
            realMask = QString("%1.%2.%3.%4")
                .arg((mask >> 24) & 0xFF)
                .arg((mask >> 16) & 0xFF)
                .arg((mask >> 8) & 0xFF)
                .arg(mask & 0xFF);
        }
        
        // 2. 获取master接口信息
        QString masterInterface;
        QProcess nmcliProc;
        nmcliProc.start("nmcli", QStringList() << "connection" << "show" << conn.name);
        nmcliProc.waitForFinished(1000);
        QString nmcliOut = QString::fromUtf8(nmcliProc.readAllStandardOutput());
        for (const QString &line : nmcliOut.split('\n')) {
            QString tline = line.trimmed();
            if (tline.startsWith("connection.master:")) {
                masterInterface = tline.section(':', 1).trimmed();
                break;
            }
        }
        
        // 3. 如果找到master接口，获取其DHCP状态
        if (!masterInterface.isEmpty()) {
            QProcess masterProc;
            masterProc.start("nmcli", QStringList() << "connection" << "show" << masterInterface);
            masterProc.waitForFinished(1000);
            QString masterOut = QString::fromUtf8(masterProc.readAllStandardOutput());
            for (const QString &line : masterOut.split('\n')) {
                QString tline = line.trimmed();
                if (tline.startsWith("ipv4.method:")) {
                    QString method = tline.section(':', 1).trimmed();
                    if (method == "auto") {
                        realDhcp = "是";
                    }
                    break;
                }
            }
        }
        
        // 4. 覆盖显示
        vals << realDhcp;
        vals << realIp;
        vals << realMask;
        vals << realGw;
        vals << realDns;
        // 其余字段保持原逻辑
        vals << ""; // WINS
        vals << "否"; // NetBIOS
        vals << ""; // IPv6
        vals << ""; // IPv6 GW
    } else {
        // 原有逻辑
    QString dhcpText = "否";
    if (conn.ipv4Method == "auto" || conn.dhcp) {
        dhcpText = "是";
    }
    vals << dhcpText;
    vals << (!conn.ipAddress.isEmpty() ? conn.ipAddress : dev.ipAddress);
    vals << (!conn.netmask.isEmpty() ? conn.netmask : dev.netmask);
    vals << (!conn.gateway.isEmpty() ? conn.gateway : dev.gateway);
    // DNS分行显示
    QString dnsDisplay;
    bool isManualIP = (conn.ipv4Method == "manual");
        bool isAutoDNS = (conn.dns.isEmpty() && !conn.dhcp && !conn.netbios);
    bool ignoreAutoDNS = false;
    QProcess proc;
    proc.start("nmcli", QStringList() << "connection" << "show" << conn.name);
    proc.waitForFinished(1000);
    QString output = proc.readAllStandardOutput();
    for (const QString &line : output.split('\n')) {
        if (line.trimmed().startsWith("ipv4.ignore-auto-dns:")) {
            QString val = line.section(':', 1).trimmed().toLower();
            ignoreAutoDNS = (val == "yes" || val == "是" || val == "true" || val == "1");
            break;
        }
    }
    if (isManualIP && conn.dns.isEmpty() && !ignoreAutoDNS) {
        QFile resolv("/etc/resolv.conf");
        if (resolv.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QStringList dnsList;
            while (!resolv.atEnd()) {
                QString line = resolv.readLine().trimmed();
                if (line.startsWith("nameserver")) {
                    dnsList << line.section(' ', 1, 1);
                }
            }
            dnsDisplay = dnsList.join("\n");
        }
    } else {
    QString dns = !conn.dns.isEmpty() ? conn.dns : dev.dns;
    QStringList dnsList = dns.split(QRegularExpression("[ ,;]+"), Qt::SkipEmptyParts);
        dnsDisplay = dnsList.join("\n");
    }
    vals << dnsDisplay;
    vals << (!conn.wins.isEmpty() ? conn.wins : "");
    vals << (conn.netbios ? "是" : "否");
    vals << (!conn.ipv6Address.isEmpty() ? conn.ipv6Address : dev.ipv6Address);
    vals << (!conn.ipv6Gateway.isEmpty() ? conn.ipv6Gateway : dev.ipv6Gateway);
    }
    // 保证长度一致
    while (vals.size() < props.size()) vals << "";
    while (vals.size() > props.size()) vals.removeLast();
    table->setRowCount(props.size());
    int rowHeight = 28; // 行高
    for (int i = 0; i < props.size(); ++i) {
        table->setItem(i, 0, new QTableWidgetItem(props[i]));
        QTableWidgetItem *valItem = new QTableWidgetItem(vals[i]);
        if (props[i] == "IPv4 DNS 服务器") {
            valItem->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
            valItem->setData(Qt::DisplayRole, vals[i]);
            valItem->setFlags(valItem->flags() & ~Qt::ItemIsEditable);
            valItem->setToolTip(vals[i]);
            valItem->setText(vals[i]);
            valItem->setFont(QFont("微软雅黑", 10));
            valItem->setForeground(QBrush(QColor("#222")));
            valItem->setBackground(QBrush(QColor("#fff")));
            valItem->setWhatsThis("dns");
            valItem->setData(Qt::UserRole, vals[i]);
            valItem->setData(Qt::EditRole, vals[i]);
            valItem->setData(Qt::DisplayRole, vals[i]);
            valItem->setData(Qt::ToolTipRole, vals[i]);
            valItem->setData(Qt::StatusTipRole, vals[i]);
            valItem->setData(Qt::AccessibleTextRole, vals[i]);
            valItem->setData(Qt::AccessibleDescriptionRole, vals[i]);
            valItem->setData(Qt::UserRole + 1, true); // 标记为多行
            int lines = vals[i].count('\n') + 1;
            table->setRowHeight(i, 28 * lines);
        } else {
            table->setRowHeight(i, rowHeight);
        }
        table->setItem(i, 1, valItem);
    }
    int headerH = table->horizontalHeader()->height();
    int totalH = headerH;
    for (int i = 0; i < table->rowCount(); ++i) totalH += table->rowHeight(i);
    table->setFixedHeight(totalH + 2); // +2 for border
    this->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding);
    this->adjustSize();
} 